package com.doudou.collection.infrastructure.core.ex.handler;

import com.doudou.collection.infrastructure.common.ex.ServiceException;
import com.doudou.collection.infrastructure.common.web.ResultVO;
import com.doudou.collection.infrastructure.common.web.StatusCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @ClassName GlobalExceptionHandler<br>
 * @Description 全局异常处理类<br>
 * @Author 李浩文<br>
 * @Date 2023/6/3 11:17<br>
 * @Version 1.0<br>
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 用户名或密码错误抛出的异常
     */
    @ExceptionHandler({
            InternalAuthenticationServiceException.class,
            BadCredentialsException.class
    })
    public ResultVO handleAuthenticationException(AuthenticationException e) {
        log.debug("全局异常处理器开始处理AuthenticationException");
        log.debug("异常类型：{}", e.getClass().getName());
        String message = "登录失败，用户名或密码错误！";
        return new ResultVO(StatusCode.ERROR_UNAUTHORIZED.getCode(), message);
    }

    /**
     * 业务逻辑层抛出的异常
     */
    @ExceptionHandler
    public ResultVO handleServiceException(ServiceException e) {
        log.error("全局异常开始处理ServiceException: {}", e.getMessage());
        return new ResultVO(e.getServiceCode(), e.getMessage());
    }

    @ExceptionHandler
    public ResultVO handlerBindException(BindException e) {
        log.debug("全局异常开始处理BindException");

        StringBuilder sb = new StringBuilder();
        sb.append("请求参数格式错误：");
        sb.append(e.getFieldError().getDefaultMessage());
        sb.append("!");
        String message = sb.toString();
        log.warn(message);
        return new ResultVO(StatusCode.FAILED, message);
    }

    @ExceptionHandler
    public ResultVO handleThrowable(Throwable e) {
        log.error("全局异常开始处理Throwable: {}", e.getMessage());
        return new ResultVO(StatusCode.ERROR_UNKNOWN);
    }
}










